﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.IO;
using System.Xml;
using System.Windows.Forms;
using Common;

namespace WoodManager.UI {

    public partial class ChiTietModule : Form
    {
        ConnectManager cm = new ConnectManager();
        Validator vali = new Validator();
        public DataTable tbGrid;
        DataTable tbLoiVan, tbPhuMat1, tbPhuMat2, tbThanhPhan;
        bool isLoad = false;
        string sModuleID = "", sChiTietIdOld = "";
        string sNhomModule = "";
        public bool isAcceptLoad = false;

        public ChiTietModule()
        {
            InitializeComponent();
            //loadData();
            loadTreeVIew();
            loadVanLoi();
            isLoad = true;
            loadSonPhu();
        }

        private void loadVanLoi()
        {
            tbLoiVan = cm.getTable("select IDVan, TenVan from ViewVanVatLieu order by NhomVan ");
            cbbMaLoiVan.DataSource = tbLoiVan;
            cbbMaLoiVan.DisplayMember = "TenVan";
            cbbMaLoiVan.ValueMember = "IDVan";
        }

        private void loadSonPhu()
        {
            if ((tbLoiVan.Rows.Count > 0) && (isLoad) && (cbbMaLoiVan.SelectedIndex > -1))
            {
                tbPhuMat1 = cm.getTable("select SonPhu.IDSon, SonPhu.ChiTiet from sonphu, tohopvanson"
                                        + " where SonPhu.IDSon = ToHopVanSon.IDSon "
                                        + " and ToHopVanSon.IDVan = N'" + cbbMaLoiVan.SelectedValue + "'");
                cbbPhuMat1.DataSource = tbPhuMat1;
                cbbPhuMat1.DisplayMember = "ChiTiet";
                cbbPhuMat1.ValueMember = "IDSon";

                tbPhuMat2 = cm.getTable("select SonPhu.IDSon, SonPhu.ChiTiet from sonphu, tohopvanson"
                        + " where SonPhu.IDSon = ToHopVanSon.IDSon "
                        + " and ToHopVanSon.IDVan = N'" + cbbMaLoiVan.SelectedValue + "'");
                cbbPhuMat2.DataSource = tbPhuMat2;
                cbbPhuMat2.DisplayMember = "ChiTiet";
                cbbPhuMat2.ValueMember = "IDSon";
            }
        }

        private void loadTreeVIew()
        {
            DataTable tbNhom;

            if (cm.conn.State == ConnectionState.Closed)
                cm.conn.Open();
            treeView1.Nodes.Clear();
            tbNhom = cm.getTable("Select * from NhomModule");

            TreeNode tnLevel1;
            for (int i = 0; i < tbNhom.Rows.Count; i++)
            {
                DataTable tbPhanNhom = cm.getTable("Select * from PhanNhomModule where NhomID = N'"
                                            + tbNhom.Rows[i]["NhomModuleID"].ToString() + "'");
                if (tbPhanNhom.Rows.Count > 0)
                {
                    TreeNode[] tnLevel2 = new TreeNode[tbPhanNhom.Rows.Count];
                    for (int i2 = 0; i2 < tbPhanNhom.Rows.Count; i2++)
                    {
                        DataTable tbTenModule = cm.getTable("select * from Module where NhomModuleID = N'"
                                                    + tbPhanNhom.Rows[i2]["PhanNhomID"].ToString() + "'");
                        if (tbTenModule.Rows.Count > 0)
                        {
                            TreeNode[] tnLevel3 = new TreeNode[tbTenModule.Rows.Count];
                            for (int i3 = 0; i3 < tbTenModule.Rows.Count; i3++)
                            {
                                tnLevel3[i3] = new TreeNode(tbTenModule.Rows[i3]["TenModule"].ToString());
                                tnLevel3[i3].Name = tbTenModule.Rows[i3]["ModuleID"].ToString();
                            }
                            tnLevel2[i2] = new TreeNode(tbPhanNhom.Rows[i2]["TenPhanNhom"].ToString(), tnLevel3);
                        }
                        else
                        {
                            tnLevel2[i2] = new TreeNode(tbPhanNhom.Rows[i2]["TenPhanNhom"].ToString());
                        }
                        tnLevel2[i2].Name = tbPhanNhom.Rows[i2]["PhanNhomID"].ToString();
                    }
                    tnLevel1 = new TreeNode(tbNhom.Rows[i]["TenNhomModule"].ToString(), tnLevel2);
                }
                else
                {
                    tnLevel1 = new TreeNode(tbNhom.Rows[i]["TenNhomModule"].ToString());
                }
                tnLevel1.Name = tbNhom.Rows[i]["NhomModuleID"].ToString();
                treeView1.Nodes.Add(tnLevel1);
            }
            if (cm.conn.State == ConnectionState.Open)
                cm.conn.Close();
        }

        private void loadDataGrid(string moduleID)
        {
            // Load data to list
            tbGrid = cm.getTable("select * from ViewModuleDetails where ModuleId = N'" + moduleID + "'");
            dtgModuleDetail.DataSource = tbGrid;

            for (int u = 0; u < tbGrid.Columns.Count; u++)
            {
                if ((tbGrid.Columns[u].ColumnName == "ModuleId")
                    || (tbGrid.Columns[u].ColumnName == "MaLoiVan")
                    || (tbGrid.Columns[u].ColumnName == "SonPhu1")
                    || (tbGrid.Columns[u].ColumnName == "SonPhu2")
                    )
                {
                    dtgModuleDetail.Columns[u].Visible = false;
                }
            }

            // Load "thanh phan" to combobox
            tbThanhPhan = cm.getTable("Select distinct ThanhPhan from ViewModuleDetails where ModuleId = N'" + moduleID + "'");
            cbbThanhPhan.DataSource = tbThanhPhan;
            cbbThanhPhan.DisplayMember = "ThanhPhan";
            cbbThanhPhan.ValueMember = "ThanhPhan";

            // focus to cell on list
            if (sChiTietIdOld != "")
            {
                for (int i = 0; i < tbGrid.Rows.Count; i++)
                {
                    if (sChiTietIdOld == tbGrid.Rows[i]["ChiTietID"].ToString())
                    {
                        dtgModuleDetail.CurrentCell = dtgModuleDetail[0, i];
                        cbbThanhPhan.SelectedValue = tbGrid.Rows[i]["ThanhPhan"].ToString();
                        break;
                    }
                }
            }
        }

        private void CalSquare()
        {
            //switch (cbbSoCanhSon.SelectedValue.ToString())
            //{
            //    case "0":
            //        LenCanh = 0.0;
            //        break;
            //    case "1":
            //        LenCanh = dDai * double.Parse(txtSoLuong.Text) / 1000;
            //        break;
            //    case "2":
            //        LenCanh = dRong * double.Parse(txtSoLuong.Text) / 1000;
            //        break;
            //    case "3":
            //        LenCanh = (dDai + dRong) * double.Parse(txtSoLuong.Text) / 1000;
            //        break;
            //    case "4":
            //        LenCanh = (dDai + 2 * dRong) * double.Parse(txtSoLuong.Text) / 1000;
            //        break;
            //    case "5":
            //        LenCanh = (2 * dDai + dRong) * double.Parse(txtSoLuong.Text) / 1000;
            //        break;
            //    case "6":
            //        LenCanh = 2 * dRong * double.Parse(txtSoLuong.Text) / 1000;
            //        break;
            //    case "7":
            //        LenCanh = 2 * dDai * double.Parse(txtSoLuong.Text) / 1000;
            //        break;
            //    case "8":
            //        LenCanh = (dDai + dRong) * 2 * double.Parse(txtSoLuong.Text) / 1000;
            //        break;
            //}

        }


        private void treeModule_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            //treeView1.CollapseAll();
            //e.Node.Expand();
            if (e.Node.Level == 2)
            {
                sModuleID = e.Node.Name;
                loadDataGrid(sModuleID);
                btnAdd.Enabled = true;
            }
            else
            {
                sModuleID = "";
                dtgModuleDetail.DataSource = null;
                btnAdd.Enabled = false;
            }
            btnDelete.Enabled = false;
            btnChange.Enabled = false;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (sModuleID == "")
            {
                MessageBox.Show("Phải chọn module trước khi thêm chi tiết");
                return;
            }

            if (txtGhiChu.Text == "")
            {
                txtGhiChu.Text = " ";
            }

            try
            {
                if (cm.conn.State == ConnectionState.Closed)
                    cm.conn.Open();
                string sInsert = "ModuleDetails_add N'" + sModuleID + "'"
                            + " ,N'" + txtMaChiTiet.Text + "'"
                            + " ,N'" + txtTenChiTiet.Text + "'"
                            + " ,N'" + txtSoLuong.Text + "'"
                            + " ,N'" + txtDai.Text + "'"
                            + " ,N'" + txtRong.Text + "'"
                            + " ,N'" + cbbThanhPhan.Text + "'"
                            + " ,N'" + cbbMaLoiVan.SelectedValue.ToString() + "'"
                            + " ,N'" + cbbPhuMat1.SelectedValue.ToString() + "'"
                            + " ,N'" + cbbPhuMat2.SelectedValue.ToString() + "'"
                            + " ,N'" + txtGhiChu.Text + "'";

                SqlCommand sqlInsert = new SqlCommand(sInsert, cm.conn);

                sqlInsert.ExecuteNonQuery();
                sChiTietIdOld = txtMaChiTiet.Text;
                btnDelete.Enabled = true;
                btnChange.Enabled = true;
                loadDataGrid(sModuleID);

                if (cm.conn.State == ConnectionState.Open)
                    cm.conn.Close();
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("PK_ModuleDetails"))
                {
                    MessageBox.Show("Đã có chi tiết này trong database");
                }
                else
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
        
        public void setVisibleButtonImport()
        {
            btnInsert.Visible = true;
        }

        private void btnInsert_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Load data từ mudule vào phiếu Phiếu đề xuất ván?", 
                                "Confirm", 
                                MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                isAcceptLoad = true;
            }
            else
            {
                isAcceptLoad = false;
            }
            this.Close();
        }

        private void btnChange_Click(object sender, EventArgs e)
        {
            if (sModuleID == "")
            {
                MessageBox.Show("Phải chọn module trước khi thêm chi tiết");
                return;
            }
            try
            {
                if (cm.conn.State == ConnectionState.Closed)
                    cm.conn.Open();
                string sInsert = "ModuleDetails_Update N'" + sModuleID + "'"
                            + " ,N'" + txtMaChiTiet.Text + "'"
                            + " ,N'" + txtTenChiTiet.Text + "'"
                            + " ,N'" + txtSoLuong.Text + "'"
                            + " ,N'" + txtDai.Text + "'"
                            + " ,N'" + txtRong.Text + "'"
                            + " ,N'" + cbbThanhPhan.Text + "'"
                            + " ,N'" + cbbMaLoiVan.SelectedValue.ToString() + "'"
                            + " ,N'" + cbbPhuMat1.SelectedValue.ToString() + "'"
                            + " ,N'" + cbbPhuMat2.SelectedValue.ToString() + "'"
                            + " ,N'" + txtGhiChu.Text + "'"
                            + " ,N'" + sChiTietIdOld + "'";

                SqlCommand sqlInsert = new SqlCommand(sInsert, cm.conn);

                sqlInsert.ExecuteNonQuery();

                sChiTietIdOld = txtMaChiTiet.Text;
                btnDelete.Enabled = true;
                loadDataGrid(sModuleID);

                sChiTietIdOld = txtMaChiTiet.Text;

                if (cm.conn.State == ConnectionState.Open)
                    cm.conn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dtgModuleDetail_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            // Click on column header
            if (e.RowIndex == -1)
                return;

            // Set data to control to edit
            txtTenChiTiet.Text = this.tbGrid.Rows[e.RowIndex]["TenChiTiet"].ToString();
            txtMaChiTiet.Text = this.tbGrid.Rows[e.RowIndex]["ChiTietID"].ToString();
            cbbThanhPhan.SelectedValue = this.tbGrid.Rows[e.RowIndex]["ThanhPhan"].ToString();
            txtDai.Text = this.tbGrid.Rows[e.RowIndex]["Dai"].ToString();
            txtRong.Text = this.tbGrid.Rows[e.RowIndex]["Rong"].ToString();
            txtSoLuong.Text = this.tbGrid.Rows[e.RowIndex]["Soluong"].ToString();
            cbbMaLoiVan.SelectedValue = tbGrid.Rows[e.RowIndex]["MaLoiVan"].ToString();
            cbbPhuMat1.SelectedValue = tbGrid.Rows[e.RowIndex]["SonPhu1"].ToString();
            cbbPhuMat2.SelectedValue = tbGrid.Rows[e.RowIndex]["SonPhu2"].ToString();
            txtGhiChu.Text = tbGrid.Rows[e.RowIndex]["GhiChu"].ToString();

            sChiTietIdOld = this.tbGrid.Rows[e.RowIndex]["ChiTietID"].ToString();
            btnDelete.Enabled = true;
            btnChange.Enabled = true;
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (sModuleID == "")
            {
                MessageBox.Show("Phải chọn module trước khi thêm chi tiết");
                return;
            }
            try
            {
                if (cm.conn.State == ConnectionState.Closed)
                    cm.conn.Open();
                string sInsert = "ModuleDetails_delete N'" + sModuleID + "'"
                            + " ,N'" + txtMaChiTiet.Text + "'";                            

                SqlCommand sqlInsert = new SqlCommand(sInsert, cm.conn);

                sqlInsert.ExecuteNonQuery();
                sChiTietIdOld = "";
                btnDelete.Enabled = false;
                btnChange.Enabled = false;

                txtTenChiTiet.Text = "";
                txtMaChiTiet.Text = "";
                txtDai.Text = "";
                txtRong.Text = "";
                txtSoLuong.Text = "";
                txtGhiChu.Text = "";

                loadDataGrid(sModuleID);

                sChiTietIdOld = txtMaChiTiet.Text;

                if (cm.conn.State == ConnectionState.Open)
                    cm.conn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void ctxTreeModule_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            //if (e.ClickedItem.Name == "makeCopy")
            //{
            //    CopyModule frmCopy = new CopyModule();

            //    frmCopy.loadTree = new CopyModule.loadTreeView(loadTreeView);

            //    frmCopy.ShowDialog();
            //}
        }

        private void deleteModuleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("bạn có chắc muốn xóa Module này không?", 
                        "Xác nhận xóa", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    if (cm.conn.State == ConnectionState.Closed)
                        cm.conn.Open();

                    SqlCommand sqlDelModuleDetails = new SqlCommand("Delete ModuleDetails where ModuleID = N'"
                                                + sModuleID + "'", cm.conn);
                    SqlCommand sqlDelModule = new SqlCommand("Delete Module where ModuleID = N'"
                                                + sModuleID + "'", cm.conn);
                    sqlDelModuleDetails.ExecuteNonQuery();
                    sqlDelModule.ExecuteNonQuery();

                    MessageBox.Show("Đã xóa module thành công");
                    loadTreeVIew();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void cbbMaLoiVan_SelectedIndexChanged(object sender, EventArgs e)
        {
            loadSonPhu();
        }

    } // End class
} // End nameSpace
